//
//  RELoginViewController.m
//  录音
//
//  Created by ywy on 2016/12/22.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "RELoginViewController.h"
#import "FirstViewController.h"
#import "RETabBarViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "RECheckLogin.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "WXApi.h"



@interface RELoginViewController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *firstLayout;

@end

@implementation RELoginViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:)  name:@"WXLogin" object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (REScreenH>667) {
        self.firstLayout.constant = 80;
    }
    // Do any additional setup after loading the view from its nib.
}
- (void) test:(NSNotification*)notification
{
    
     NSLog(@"%@ === %@ === %@", notification.object, notification.userInfo, notification.name);
    
    NSDictionary * dict = notification.object;
    
    [self getWeiXinOpenId:dict[@"code"]];
}
- (void)getWeiXinOpenId:(NSString *)code{
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAppKey,WXAppSercert,code];
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data){
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
//                if ([[dic[@"errcode"] stringValue]  isEqualToString:@"40029"]) {
//                    
////                    [weakSelf refreshWX:dic];
//                }else
//                {
////                    NSString *openID = dic[@"openid"];
////                    NSString * accessToken = dic[@"access_token"];
//                    [weakSelf getUserInfo:dic];
//                }
                 [weakSelf getUserInfo:dic];
            }else{
                [SVProgressHUD showErrorWithStatus:@"授权失败,请重新登陆"];
            }
        });
    });
}
-(void)refreshWX:(NSDictionary*)dict
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",WXAppKey,dict[@"refresh_token"]];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data){
                NSLog(@"打印数据流%@",data);
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                [weakSelf getUserInfo:dic];
            }else{
                [SVProgressHUD showErrorWithStatus:@"授权失败,请重新登陆"];
            }
        });
    });

}

-(void)getUserInfo:(NSDictionary*)dict
{
    
    
    
    
    __weak typeof(self) Weakself  = self;
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",dict[@"access_token"],dict[@"openid"]];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            if (data){
                
                NSLog(@"得到用户的信息%@",data);
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                
                [Weakself wxLoginPost:dic];
            }
        });
    });
}
-(void)wxLoginPost:(NSDictionary*)dict
{
    NSMutableDictionary * pram = [NSMutableDictionary new];
    /*  cmd = thirdLogin;
    nickName = wely;
    thirdUid = oBk9cwf1I7IUoIQiSdG8lq5N4P9A;
    userIcon = "http://wx.qlogo.cn/mmopen/9pv5baRwCMrIPpvicVrt2dbGACA7dNDoplolQxQIWBCBNcDAMgr5xBZC5LeLzOl18dWDNE6Dqs0VgFPbcUYIfR1t2VEBfclrY/0";*/
    
    pram[@"cmd"] = @"thirdLogin";
    pram[@"thirdUid"] = dict[@"unionid"];
    pram[@"nickName"] = dict[@"nickname"];
    pram[@"userIcon"] =dict[@"headimgurl"];
    [SVProgressHUD showWithStatus:@"微信登录中"];
    [RECheckLogin POST:REBaseUrl parameters:pram progress:^(CGFloat prosser) {
    } success:^(id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            
            // 此处用于登陆
            [SVProgressHUD showSuccessWithStatus:responseObject[@"resultNote"]];
            [UserDefaults setObject:responseObject[@"uid"] forKey:@"userid"];
//             [UserDefaults setObject:@"007" forKey:@"userid"];
            [self dismissViewControllerAnimated:YES completion:nil];
            [UIApplication sharedApplication].keyWindow.rootViewController = [[RETabBarViewController alloc] init];
        }else
        {
            [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
        }
          [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        NSLog(@"打印错误的信息%@",error);
        [SVProgressHUD showErrorWithStatus:@"查看网络！！"];
    }];
    
}


- (IBAction)wxLoginClick:(UIButton *)sender {
    
    
    
    if ([WXApi isWXAppInstalled]  == NO) {
        [SVProgressHUD showErrorWithStatus:@"微信未安装！ 无法登陆"];
        [UserDefaults setObject:@"007" forKey:@"userid"];
        [self dismissViewControllerAnimated:YES completion:nil];
        [UIApplication sharedApplication].keyWindow.rootViewController = [[RETabBarViewController alloc] init];
        
    }else
    {
        //构造SendAuthReq结构体
        SendAuthReq* req =[[SendAuthReq alloc ] init ];
        req.scope = @"snsapi_userinfo" ;
        req.state = @"123" ;//用于在OnResp中判断是哪个应用向微信发起的授权，这里填写的会在OnResp里面被微信返回
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
        

    }
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
       [[NSNotificationCenter  defaultCenter] removeObserver:self  name:@"WXLogin" object:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
